 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.entity.SwCkStatementConfirmAppWechat;
import com.zdkj.subway.rca.entity.SwCkStatementConfirmAppWechatTmp;
import com.zdkj.subway.rca.mapper.SwCkStatementConfirmAppWechatTmpMapper;
import com.zdkj.subway.rca.service.SwCkStatementConfirmAppWechatService;
import com.zdkj.subway.rca.service.SwCkStatementConfirmAppWechatTmpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.ZoneId;
import java.util.*;

/**
 * 西安地微信小程序对账确认表临时表
 *
 * @author lcl
 * @date 13点47分
 */
@Service
public class SwCkStatementConfirmAppWechatTmpServiceImpl extends ServiceImpl<SwCkStatementConfirmAppWechatTmpMapper, SwCkStatementConfirmAppWechatTmp> implements SwCkStatementConfirmAppWechatTmpService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkStatementConfirmAppWechatTmpServiceImpl.class);
    private String parsePattern = "yyyy-MM-dd";
    @Autowired
    private SwCkStatementConfirmAppWechatService swCkStatementConfirmAppWechatService;

    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
        //TODO 因为标题存在相同的名称，不能使用此方法
        //final Workbook workbook = ExcelUtil.chooseWorkbook(excelFile);
        //final Sheet sheet = workbook.getSheetAt(0);
        //final RcaIExcelParser excelParser = new RcaCommonExcelParse();
        ////此处固定excel标题头第几行开始，第几列结束
        //int rowNum = 2;
        //int count = 10;
        //final List<SwCkStatementConfirmAppWechatTmp> listParser = excelParser.parse(sheet, new SwCkStatementConfirmAppWechatTmp(),rowNum,count);
        //if (CollectionUtil.isNotEmpty(listParser)) {
        //    List<SwCkStatementConfirmAppQrConsumeTmp> listDb = new ArrayList<>();
        //    MultipartFileToFile.delteTempFile(excelFile);
        //    for (SwCkStatementConfirmAppQrConsumeTmp tmpObj : listParser) {
        //        if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())
        //                || StringUtils.isEmpty(tmpObj.getCountTmp())
        //                || StringUtils.isEmpty(tmpObj.getMoneyTmp())
        //                || StringUtils.isEmpty(tmpObj.getServiceChargeTmp())) {
        //            continue;
        //        }
        //        if (!parseDate(tmpObj.getTradeDateTmp())) {
        //            continue;
        //        }
        //        final SwCkStatementConfirmAppWechatTmp obj = ObjectUtils.getDefaultObj(SwCkStatementConfirmAppWechatTmp.class);
        //        BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
        //        checkErr(obj);
        //        listDb.add(obj);
        //    }
        //    Map<String, Object> columnMap = new HashMap<>();
        //    columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
        //    this.baseMapper.deleteByMap(columnMap);
        //    return this.saveBatch(listDb);
        //}
        //
        //return false;
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(3).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            List<SwCkStatementConfirmAppWechatTmp> listDb = new ArrayList<>();
            MultipartFileToFile.delteTempFile(excelFile);
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 表示所在的列 和所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

                SwCkStatementConfirmAppWechatTmp tmpObj = new SwCkStatementConfirmAppWechatTmp();
                tmpObj.setTradeDateTmp(data.get(0));//交易日期

                tmpObj.setCountTmp(Optional.ofNullable(data.get(1)).orElse("0"));
                tmpObj.setMoneyTmp(Optional.ofNullable(data.get(2)).orElse("0"));
                tmpObj.setServiceChargeTmp(Optional.ofNullable(data.get(3)).orElse("0"));
                tmpObj.setCountSubwayTmp(Optional.ofNullable(data.get(4)).orElse("0"));

                tmpObj.setMoneySubwayTmp(Optional.ofNullable(data.get(5)).orElse("0"));
                tmpObj.setServiceChargeSubwayTmp(Optional.ofNullable(data.get(6)).orElse("0"));
                tmpObj.setCountZhimaTmp(Optional.ofNullable(data.get(7)).orElse("0"));
                tmpObj.setMoneyZhimaTmp(Optional.ofNullable(data.get(8)).orElse("0"));

                tmpObj.setServiceChargeZhimaTmp(Optional.ofNullable(data.get(9)).orElse("0"));

                if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())
                        || StringUtils.isEmpty(tmpObj.getCountTmp())
                        || StringUtils.isEmpty(tmpObj.getMoneyTmp())
                        || StringUtils.isEmpty(tmpObj.getServiceChargeTmp())
                ) {
                    continue;
                }
                if (!parseDate(tmpObj.getTradeDateTmp())) {
                    continue;
                }

                final SwCkStatementConfirmAppWechatTmp obj = ObjectUtils.getDefaultObj(SwCkStatementConfirmAppWechatTmp.class);
                BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                checkErr(obj);
                listDb.add(obj);

            }
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return this.saveBatch(listDb);

        }

        return false;
    }

    private void checkErr(SwCkStatementConfirmAppWechatTmp obj) {
        //更新字段
        String tradeDateTmp = obj.getTradeDateTmp();
        try {
            Date tradeDate = DateUtils.parseDate(tradeDateTmp, parsePattern);
            obj.setTradeDate(tradeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        } catch (Exception e) {
            obj.setErrMsg("交易日期 为空或格式错误");
        }

        try {
            String countTmp = obj.getCountTmp();
            Long count = Long.parseLong(countTmp);
            obj.setCount(count);
        } catch (Exception e) {
            obj.setErrMsg("笔数 为空或格式错误");
        }

        try {
            String moneyTmp = obj.getMoneyTmp();
            BigDecimal money = new BigDecimal(moneyTmp);
            BigDecimal num = new BigDecimal("100");
            money = money.multiply(num);
            obj.setMoney(money.longValue());
        } catch (Exception e) {
            obj.setErrMsg("金额 为空或格式错误");
        }
       
        try {
            String serviceChargeTmp = obj.getServiceChargeTmp();
            BigDecimal serviceCharge = new BigDecimal(serviceChargeTmp);
            BigDecimal num = new BigDecimal("100");
            serviceCharge = serviceCharge.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
            obj.setServiceCharge(serviceCharge.longValue());
        } catch (Exception e) {
            obj.setErrMsg("手续费 为空或格式错误");
        }
       //
		  try {
            String countSubwayTmp = obj.getCountSubwayTmp();
            if(StringUtils.isEmpty(countSubwayTmp)){
                countSubwayTmp = "0";
            }
            Long countSubway = Long.parseLong(countSubwayTmp);
            obj.setCountSubway(countSubway);
        } catch (Exception e) {
            obj.setErrMsg("地铁账户笔数 为空或格式错误");
        }

        try {
            String moneySubwayTmp = obj.getMoneySubwayTmp();
            if(StringUtils.isEmpty(moneySubwayTmp)){
                moneySubwayTmp = "0";
            }
            BigDecimal moneySubway = new BigDecimal(moneySubwayTmp);
            BigDecimal num = new BigDecimal("100");
            moneySubway = moneySubway.multiply(num);
            obj.setMoneySubway(moneySubway.longValue());
        } catch (Exception e) {
            obj.setErrMsg("地铁账户金额 为空或格式错误");
        }

        try {
            String serviceChargeSubwayTmp = obj.getServiceChargeSubwayTmp();
            if(StringUtils.isEmpty(serviceChargeSubwayTmp)){
                serviceChargeSubwayTmp = "0";
            }
            BigDecimal serviceChargeSubway = new BigDecimal(serviceChargeSubwayTmp);
            BigDecimal num = new BigDecimal("100");
            serviceChargeSubway = serviceChargeSubway.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
            obj.setServiceChargeSubway(serviceChargeSubway.longValue());
        } catch (Exception e) {
            obj.setErrMsg("地铁账户手续费 为空或格式错误");
        }

		try {
            String countZhimaTmp = obj.getCountZhimaTmp();
            if(StringUtils.isEmpty(countZhimaTmp)){
                countZhimaTmp = "0";
            }
            Long countZhima = Long.parseLong(countZhimaTmp);
            obj.setCountZhima(countZhima);
        } catch (Exception e) {
            obj.setErrMsg("智码账户笔数 为空或格式错误");
        }

        try {
            String moneyZhimaTmp = obj.getMoneyZhimaTmp();
            if(StringUtils.isEmpty(moneyZhimaTmp)){
                moneyZhimaTmp = "0";
            }
            BigDecimal moneyZhima = new BigDecimal(moneyZhimaTmp);
            BigDecimal num = new BigDecimal("100");
            moneyZhima = moneyZhima.multiply(num);
            obj.setMoneyZhima(moneyZhima.longValue());
        } catch (Exception e) {
            obj.setErrMsg("智码账户金额 为空或格式错误");
        }

        try {
            String serviceChargeZhimaTmp = obj.getServiceChargeZhimaTmp();
            if(StringUtils.isEmpty(serviceChargeZhimaTmp)){
                serviceChargeZhimaTmp = "0";
            }
            BigDecimal serviceChargeZhima = new BigDecimal(serviceChargeZhimaTmp);
            BigDecimal num = new BigDecimal("100");
            serviceChargeZhima = serviceChargeZhima.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
            obj.setServiceChargeZhima(serviceChargeZhima.longValue());
        } catch (Exception e) {
            obj.setErrMsg("智码账户手续费 为空或格式错误");
        }

        //判断数据是否存在
        SwCkStatementConfirmAppWechat swCkStatementConfirmAppWechat = new SwCkStatementConfirmAppWechat();
        BeanUtils.copyProperties(obj, swCkStatementConfirmAppWechat, "deptId","creatorId","creatorName","createTime");
        List<SwCkStatementConfirmAppWechat> list = swCkStatementConfirmAppWechatService.list(Wrappers.query(swCkStatementConfirmAppWechat));
        if (list != null && !list.isEmpty()) {
            obj.setErrMsg("数据已存在");
        }
    }

    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            DateUtils.parseDate(string, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    @Override
    public void saveBatchWithExcelOk(Integer creatorId) {
        //导入先删除
        this.baseMapper.deleteBatchWithExcelOk(creatorId);
        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(creatorId);
        //this.baseMapper.saveBatchWithExcelOk(creatorId);
        saveBatchWithExcelCancel(creatorId);
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID", creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }
}
